﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using BingMapsSpatial.WinLoader.Utilities;
using System.Text.RegularExpressions;

namespace BingMapsSpatial.WinLoader
{
    public partial class MainForm : Form
    {
        #region Constants

        const string c_SpatialServiceFormatUrl = "http://spatial.virtualearth.net/REST/V1/Dataflows/LoadDataSource?dataSourceName={0}&loadOperation=complete&output=xml&input={3}&key={1}&queryKey={2}";

        #endregion

        public MainForm()
        {
            InitializeComponent();

            this.cboFormatType.Items.Add(new ComboBoxItem("text/xml", "xml"));
            this.cboFormatType.Items.Add(new ComboBoxItem("text/plain", "csv"));
            this.cboFormatType.Items.Add(new ComboBoxItem("text/plain", "tab"));
            this.cboFormatType.Items.Add(new ComboBoxItem("text/plain", "pipe"));
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            WebRequest request = null;
            WebResponse response = null;

            try
            {
                ComboBoxItem itm = (ComboBoxItem)this.cboFormatType.SelectedItem;
                string url = string.Format(c_SpatialServiceFormatUrl,
                                           this.tbSourceName.Text,
                                           this.tbMasterKey.Text,
                                           this.tbReaderKey.Text,
                                           itm.Text);

                FileStream fileStream = File.OpenRead(this.tbFileName.Text);
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();


                // Compose the request
                request = WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = itm.Value + "; charset=utf-8";
                request.Timeout = System.Threading.Timeout.Infinite;

                // Set the content
                MemoryStream memoryStream = new MemoryStream(bytes.Length);
                memoryStream.Write(bytes, 0, bytes.Length);

                request.ContentLength = memoryStream.Length;
                var requestStream = request.GetRequestStream();
                memoryStream.Seek(0, SeekOrigin.Begin);
                memoryStream.WriteTo(requestStream);

                response = request.GetResponse();
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                string elt = responseReader.ReadToEnd();

                string urlJob = elt.Split(new string[] { "<Link role=\"self\">" }, StringSplitOptions.None)[1].Split(new string[] { "</Link><Status>" }, StringSplitOptions.None)[0];
                this.openWebBrowser(urlJob);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while uploading the file: " + ex.Message);
            }

        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (this.openFileDialogLoader.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.tbFileName.Text = this.openFileDialogLoader.FileName;
            }
        }

        // Links

        private void openWebBrowser(string link)
        {
            System.Diagnostics.Process.Start("iexplore.exe", link);
        }

        private void lkPortal_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.openWebBrowser("http://www.bingmapsportal.com");
        }

        private void lkTwitterNico_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.openWebBrowser("http://www.twitter.com/nicolasboonaert/");            
        }

        private void lkNico_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.openWebBrowser("http://blogs.developpeur.org/nicoboo/");
        }

        private void lkWygwam_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.openWebBrowser("http://bmsdsloader.codeplex.com/");
        }

        private void lkMsdn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.openWebBrowser("http://msdn.microsoft.com/en-us/library/ff701733.aspx");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string elt = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://schemas.microsoft.com/search/local/ws/rest/v1\"><Copyright>Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright><BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri><StatusCode>201</StatusCode><StatusDescription>Created</StatusDescription><AuthenticationResultCode>ValidCredentials</AuthenticationResultCode><TraceId>815a44b731fa44ae8b9fb3ad97a5bb3b|AMSM001566|02.00.82.2300|</TraceId><ResourceSets><ResourceSet><EstimatedTotal>1</EstimatedTotal><Resources><DataflowJob><Id>1d4d815948d242fd941a882924e899ff</Id><Link role=\"self\">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/1d4d815948d242fd941a882924e899ff</Link><Status>Pending</Status><CreatedDate>2011-05-19T02:34:50.8908901-07:00</CreatedDate><CompletedDate xsi:nil=\"true\" /><TotalEntityCount>0</TotalEntityCount><ProcessedEntityCount>0</ProcessedEntityCount><FailedEntityCount>0</FailedEntityCount></DataflowJob></Resources></ResourceSet></ResourceSets></Response>";
            string urlJob = elt.Split(new string[] { "<Link role=\"self\">" }, StringSplitOptions.None)[1].Split(new string[] { "</Link><Status>" }, StringSplitOptions.None)[0];
        }
    }
}
